/*
 * thread.c
 *
 *  Created on: 1-nov-2012
 *      Author: dna
 */

#include "thread.h"


int compare (const void * a, const void * b)
{
	return ( *(char*)a - *(char*)b );
}

void *routine(void *arg) {

	int i;
	cpu_set_t cpus;
	routine_param* parameters = (routine_param*) arg;
	FILE *f;

	parameters->tid = syscall(SYS_gettid);//pthread_self();

	// per la routine di I/O
	if (parameters->cpu_bound){
		char filename[255] = "";
		sprintf(filename,"thread%d.txt",parameters->tid);
		f = fopen(filename,"w+");
	}

	// set CPU affinity
	CPU_ZERO(&cpus);
	CPU_SET(parameters->cpu,&cpus);

	pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpus);

	// check wich CPU this thread is running on
	parameters->cpu_working = sched_getcpu();

	// set sched parameters
	sched_setscheduler(0,parameters->policy,&(parameters->priority));

	// waiting the barrier
	pthread_barrier_wait(&barrier);

	// routine
	srand(time(NULL));

	for (i=0; i<parameters->values_num; i++){
		parameters->values[i] = rand();
		if (parameters->cpu_bound){
			fprintf(f,"%c ",parameters->values[i]);
		}
	}

	if (parameters->cpu_bound)
		fprintf(f,"\n\n\n");

	qsort(parameters->values,parameters->values_num,sizeof(char),compare);

	if (parameters->cpu_bound){
		for (i=0; i<parameters->values_num; i++)
			fprintf(f,"%c ",parameters->values[i]);
	}

	// get the end time
	gettimeofday(&(parameters->end), NULL);

	return (void*)0;
}
